<%-- 
    Document   : login
    Created on : Nov 15, 2010, 12:52:15 PM
    Author     : edwinelpaisa
--%>

<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page session="true"%>
<%
       String sql = "";
       String json = "";
       ResultSet res = null;
       model.ConnectionDB connection = new model.ConnectionDB();

        if(request.getParameter("action").equals("login")){
            sql = "SELECT * FROM GetUser('" + request.getParameter("user") + "','" + request.getParameter("password") + "');";
            
            try {
            connection.connect();
            connection.consult(sql);                        
            res = connection.getRes();
            
            if(res.next()){
                HttpSession sessionUser=request.getSession();//Create new Session
                sessionUser.setAttribute("result",res);
                json += "'user_id' : '" + res.getString(1) + "', ";
                json += "'user_mail' : '" + res.getString(2) + "', ";
                json += "'user_name' : '" + res.getString(3) + "', ";                    
                json += "'user_uname' : '" + res.getString(4) + "', ";
                json += "'user_telephone' : '" + res.getString(5) + "',";
                json += "'user_type' : " + res.getInt(6);
                out.print("{'errorcode' : 0, "+json+"}"); //User Exist
            }
            else
                out.print("{'errorcode' : -3}"); //User not Exists
            connection.getCon().close();
        } catch (SQLException e) {            
            out.print("{'errorcode' : -1}");//Can't connect to data base
            connection.getCon().close();
        }
       }else if(request.getParameter("action").equals("logout")){
           HttpSession sessionUser=request.getSession();
           if(sessionUser.getAttribute("result") != null){
               sessionUser.invalidate();
               out.print("{'errorcode':0}");//Session exist and close
           }else
               out.print("{'errorcode' : -1}");//No session found
       }
       else
           out.print("{'errorcode' : -2}"); //Incorrect Access        
%>